package com.taskflow.service;

import com.taskflow.entity.DownloadLog;
import com.taskflow.entity.DownloadTask;
import com.taskflow.entity.EntryData;
import com.taskflow.mapper.DownloadTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 关单下载定时任务
 */
@Slf4j
@Component
public class DownloadJob implements Job {

    @Autowired
    private DownloadTaskMapper taskMapper;

    @Autowired
    private EntryDataService entryDataService;

    @Autowired
    private DownloadLogService logService;

    @Autowired
    private ExternalApiService externalApiService;

    @Override
    public void execute(JobExecutionContext context) {
        Long taskId = context.getJobDetail().getJobDataMap().getLong("taskId");
        log.info("开始执行下载任务: taskId={}", taskId);

        DownloadTask task = taskMapper.selectById(taskId);
        if (task == null) {
            log.error("任务不存在: taskId={}", taskId);
            return;
        }

        // 创建下载日志
        DownloadLog downloadLog = new DownloadLog();
        downloadLog.setTaskId(taskId);
        downloadLog.setTaskName(task.getTaskName());
        downloadLog.setStartTime(new Date());
        downloadLog.setExecuteStatus(0); // 执行中
        logService.createLog(downloadLog);

        try {
            // 更新任务状态为运行中
            taskMapper.updateStatus(taskId, 2);

            // 调用外部API查询关单数据
            List<EntryData> entryDataList;
            
            if (StringUtils.isNotBlank(task.getCompanyTaxNo())) {
                // 使用企业税号调用外部API
                log.info("调用外部API查询关单数据: 企业税号={}, 日期范围=前{}天", 
                        task.getCompanyTaxNo(), task.getDeclareDateRange());
                entryDataList = externalApiService.queryEntryData(
                        task.getCompanyTaxNo(),
                        task.getDeclareDateRange()
                );
            } else {
                // 如果没有企业税号，从本地数据库查询（兼容旧逻辑）
                log.info("从本地数据库查询关单数据");
                entryDataList = entryDataService.getByTaskConditions(
                        task.getCompanyName(),
                        task.getCompanyTaxNo(),
                        task.getEntryId(),
                        task.getDeclareDateRange()
                );
            }

            int totalCount = entryDataList.size();
            int newCount = 0;
            int duplicateCount = 0;

            // 处理每条关单明细数据
            for (EntryData entryData : entryDataList) {
                String entryId = entryData.getEntryId();
                String gNo = entryData.getGNo();
                if (entryId == null || entryId.trim().isEmpty()) {
                    continue;
                }

                // 检查关单明细是否已存在（entryId + gNo 联合主键）
                if (entryDataService.existsByEntryIdAndGNo(entryId, gNo)) {
                    duplicateCount++;
                    log.debug("关单明细已存在，跳过: entryId={}, gNo={}", entryId, gNo);
                } else {
                    // 保存新明细数据
                    entryDataService.saveEntryData(entryData);
                    newCount++;
                    log.debug("保存新关单明细: entryId={}, gNo={}", entryId, gNo);
                }
            }

            // 更新日志
            downloadLog.setEndTime(new Date());
            downloadLog.setExecuteStatus(1); // 成功
            downloadLog.setTotalCount(totalCount);
            downloadLog.setNewCount(newCount);
            downloadLog.setDuplicateCount(duplicateCount);
            logService.updateLog(downloadLog);

            // 更新任务最后执行时间和状态
            task.setLastExecuteTime(new Date());
            task.setStatus(1); // 恢复启用状态
            taskMapper.update(task);

            log.info("下载任务执行完成: taskId={}, 总数={}, 新增={}, 重复={}",
                    taskId, totalCount, newCount, duplicateCount);

        } catch (Exception e) {
            log.error("下载任务执行失败: taskId={}", taskId, e);

            // 更新日志为失败状态
            downloadLog.setEndTime(new Date());
            downloadLog.setExecuteStatus(2); // 失败
            downloadLog.setErrorMsg(e.getMessage());
            logService.updateLog(downloadLog);

            // 恢复任务状态
            taskMapper.updateStatus(taskId, 1);
        }
    }
}

